package com.uaroadshow.finale.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.persistence.annotation.Dao;
import com.uaroadshow.entity.user.User;
import com.uaroadshow.entity.user.UserInfo;
import com.uaroadshow.entity.user.WechatAccount;
import com.uaroadshow.finale.dao.UserDao;
import com.uaroadshow.finale.service.UserService;

/**
 * 
 * @author mohanlan
 *
 */
@Service("userService")
public class UserServiceImpl extends DataServiceImpl<User> implements UserService {
    
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    
    @Dao
    private UserDao userDao;
    
    /* (non-Javadoc)
     * @see com.uaroadshow.finale.service.UserService#getUserByUnionid(java.lang.String)
     */
    public User getUserByUnionid(String unionid) {
        return userDao.getUserByUnionid(unionid);
    }
    
    /*
     * (non-Javadoc)
     * @see com.edoomath.api.servcice.UserService#create(java.lang.String)
     */
    public User create(String unionid) {
        
        logger.trace("create user ... ");
        
        // 1. create user when it is new
        User user = userDao.loadUser(unionid);
        
        // 2. get wechat account to create user
        WechatAccount account = userDao.loadAccount(unionid);
        
        if(user == null) {  // when user does not exist, create a new one
            
            if(account == null) {
                
                throw BusinessException.newInstance("400", "微信授权信息获取失败");
            }
            
            // 3. create user using unionid, openid, mobile
            user = new User(account.getUnionid(), account.getOpenid(), null);
            
            
            // update user's nickname, avatar
            genericDaoSupport.save(user.initliaze(account.getNickname(), account.getHeadimgurl()));
            
            UserInfo userInfo = new UserInfo(user);
            genericDaoSupport.save(userInfo);
        }
        
        if(StringUtils.isNoneBlank(account.getOpenid())) {
            user.bindOpenid(account.getOpenid());
        }
        
        genericDaoSupport.update(user.initliaze(account.getNickname(), account.getHeadimgurl()));
        
        return user;
    }
}
